package marmalius.tools;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBService {
	private static final DBService instance = new DBService();
	private LogService log;
	private Connection connection;
	private Config cfg;
	private ResultSet lastGeneratedKeys;
	
	public DBService() { }
	
	public boolean setConfig(Config cfg) {
		this.cfg = cfg;
		log = LogService.getInstance();
		try {
			Class.forName(cfg.getSql_Driver());
			return true;
		}
		catch (ClassNotFoundException ex) {
			LogService.getInstance().logError("Error with SQL Driver");
			LogService.getInstance().logError(ex.getMessage());
			return false;
		}
	}
	
	public boolean initSql() {
		try {
			connection = DriverManager.getConnection("jdbc:mysql://" + cfg.getSql_host()+":"+cfg.getSql_port() + "/"+ cfg.getSql_name(), cfg.getSql_login(), cfg.getSql_pass());
			log.logInfo("connected to sql server");
			return true;
		}
		catch (SQLException ex) {
			log.logError("can't connect to sql server");
			log.logError(ex.getMessage());
			return false;
		}
	}
	
	public ResultSet doQuery(String sql) throws SQLException {
		return doQuery(sql, false);
	}
	
	public ResultSet doQuery(String sql, boolean autoFirst) throws SQLException {
		Statement statement = connection.createStatement();
		ResultSet rs = statement.executeQuery(sql);
		if (autoFirst) {
			if (!rs.first())
				return null;
		}
		return rs;
	}
	
	public boolean doExecute(String sql) throws SQLException {
		Statement statement = connection.createStatement();
		boolean result = statement.execute(sql);
		if (result)
			lastGeneratedKeys = statement.getGeneratedKeys();
		else
			lastGeneratedKeys = null;
		return result;
	}
	
	public int getLastInsertId(String name) throws SQLException {
		if (lastGeneratedKeys != null && lastGeneratedKeys.first())
			return lastGeneratedKeys.getInt(name);
		else
			return 0;
	}
	
	public boolean isClosed() {
		try {
			return connection.isClosed();
		}
		catch (SQLException ex) {
			log.logError("Error with sql connect");
			log.logError(ex.getMessage());
			return false;
		}
	}
	
	public static DBService getInstance() {
		return instance;
	}
}
